<?php

namespace App\Admin\Forms;

use App\Enums\DomainType;
use App\Models\Chapter;
use App\Models\DomainPool;
use App\Models\Season;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Exception\RuntimeException;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class DomainConfigForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input): JsonResponse
    {
        $id = $this->payload['id'];
        $middle = $input['middle_target_id'];
        $player = $input['player_target_id'];
        $rank = $input['rank_target_id'];

        $model = match ($this->payload['model']) {
            'season' => Season::ofAdmin()->find($id),
            'chapter' => Chapter::ofAdmin()->find($id),
        };

        if ($middle) {
            $model->spider()->updateOrCreate([
                'type' => DomainType::MIDDLE,
            ], [
                'target_id' => $middle,
            ]);
        } else {
            $model->spider()->where('type', DomainType::MIDDLE)->delete();
        }

        if ($player) {
            $model->spider()->updateOrCreate([
                'type' => DomainType::PLAYER,
            ], [
                'target_id' => $player,
            ]);
        } else {
            $model->spider()->where('type', DomainType::PLAYER)->delete();
        }

        if ($rank) {
            $model->spider()->updateOrCreate([
                'type' => DomainType::RANK,
            ], [
                'target_id' => $rank,
            ]);
        } else {
            $model->spider()->where('type', DomainType::RANK)->delete();
        }

        return $this->response()->success('sad')->refresh();
    }

    /**
     * @throws RuntimeException
     */
    public function form(): void
    {
        $this->select('middle_target_id', '活码域名')
            ->options(DomainPool::ofAdmin()->ofEnabled()->where('type', DomainType::MIDDLE)->pluck('domain', 'id'));
        $this->select('player_target_id', '选手域名')
            ->options(DomainPool::ofAdmin()->ofEnabled()->where('type', DomainType::PLAYER)->pluck('domain', 'id'));
        $this->select('rank_target_id', '排行榜域名')
            ->options(DomainPool::ofAdmin()->ofEnabled()->where('type', DomainType::RANK)->pluck('domain', 'id'));
    }

    public function default(): array
    {
        $id = $this->payload['id'];
        $model = match ($this->payload['model']) {
            'season' => Season::ofAdmin()->find($id),
            'chapter' => Chapter::ofAdmin()->find($id),
        };

        return [
            'middle_target_id' => $model->getMiddleDomain()?->id,
            'player_target_id' => $model->getPlayerDomain()?->id,
            'rank_target_id' => $model->getRankDomain()?->id,
        ];
    }
}
